package com.sky.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 自定义定时任务，实现订单状态定时处理
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", LocalDateTime.now());

        //筛选出来未支付的订单
        List<Orders> orders = orderMapper.selectList(Wrappers.<Orders>lambdaQuery()
                .eq(Orders::getStatus, 1)
        );
        if (CollUtil.isEmpty(orders)){
            log.error("没有未支付的订单");
            return;
        }

        //获取下单时间超过15分钟的订单
        List<Orders> ordersList = orders.stream()
                .filter(x -> LocalDateTimeUtil.between(x.getOrderTime(), LocalDateTime.now(), ChronoUnit.MINUTES) > 15)
                .toList();
        if (CollUtil.isEmpty(ordersList)){
            log.error("没有超时未支付的订单");
            return;
        }

        //将其状态改为已取消
        ordersList.forEach(x-> {
            x.setStatus(6);
            orderMapper.updateById(x);
        });

    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());

        //查询状态为派送中的订单
        List<Orders> orders = orderMapper.selectList(Wrappers.<Orders>lambdaQuery()
                .eq(Orders::getStatus, 4)
        );
        if (CollUtil.isEmpty(orders)){
            log.error("没有未处理的“派送中”状态的订单");
            return;
        }

        //修改为已完成
        orders.forEach(x->{
            x.setStatus(5);
            orderMapper.updateById(x);
        });
    }

}